#include <iostream>
#include <ctype.h>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>

using std::cout;
using std::endl;
using std::cerr;
using std::string;
using std::vector;
using std::ifstream;
using std::ofstream;
using std::istringstream;

struct Record
{
    Record(const string &word, int frequency)
    : _word(word)
    , _frequency(frequency)
    {

    }
    string _word;
    int _frequency;
};

class Dictionary
{
public:
    void read(const string &filename){
        ifstream ifs(filename);
        if(!ifs){
            cerr<<"ifs is not good"<<endl;
            return;
        }
        
        string line;
        while(getline(ifs,line)){
            istringstream iss(line);
            string word;
            while(iss >> word){
                //如果单词不合法，比如abc123 abc?? 这种字符串
                string real_word = dealword(word);
                //如果是合法单词，存入vector
                insert(real_word);
            }
        }

        ifs.close();
    }

    string dealword(const string &word){   
        //&dealword，防止string类型返回时的拷贝构造，但可能返回临时对象，所以去掉&
        //const 防止右值问题
        //&word 防止形参实参结合的拷贝构造
        for(size_t idx=0;idx!=word.size();++idx){
            // if(word[idx]>='a' && word[idx]<="z");
            // if(word[idx]>='A' && word[idx]<="Z");
            if(!isalpha(word[idx]))  //返回0，代表不是字母
                return string();
        }
        return word;
    }

    //把结果写到另外一个文件里
    void store(const string &filename){
        ofstream ofs(filename);
        if(!ofs){
            cout<<"ofstream is not good"<<endl;
            return;
        }

        for(size_t idx =0; idx!= _dict.size(); ++idx){
            ofs<<_dict[idx]._word<<"        "<<_dict[idx]._frequency<<endl;
        }

        ofs.close();
    }

    void insert(const string &word){
        if(word==string())
            return;
        
        //遍历整个vector，检查当前插入的单词是否已存在
        //如果存在，则频率+1
        //主要时间都浪费在这里
        size_t idx;
        for(idx=0; idx!=_dict.size();++idx){
            if(word ==_dict[idx]._word){
                ++_dict[idx]._frequency;
                break;
            }
        }
        if(idx==_dict.size())
            _dict.push_back(Record(word,1));
            //第一次出现的单词
    }

private:
    vector<Record> _dict;
};

void test(){
   Dictionary dict;
   dict.read("The_Holy_Bible.txt");
   dict.store("4_result_vec.txt");
}

int main()
{   
    test();
    return 0;
}

